package ncme.auto.framework.core.dynamicDatasource.mybatisPlugin;

import ncme.auto.framework.core.dynamicDatasource.configs.DynamicDataSourceConfig;
import ncme.auto.framework.core.dynamicDatasource.entity.SqlConnectInfo;
import ncme.auto.framework.core.dynamicDatasource.utils.ConvertUtil;
import ncme.auto.framework.core.dynamicDatasource.utils.SQLExecutor;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Component
@Intercepts(
        {
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
        }
)
public class UpdatePlugin extends SQLExecutor implements Interceptor {

    @Autowired
    private ConvertUtil convertUtil;

    @Autowired
    private DynamicDataSourceConfig dataSourceConfig;

    /*intercept拦截：拦截目标对象的目标方法的执行*/
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result;
        if (dataSourceConfig.changeSource) {
            try {
                MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
                SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
                Object parameter = invocation.getArgs()[1];
                String sql = mappedStatement.getBoundSql(parameter).getSql();

                SqlConnectInfo sqlConnectInfo = dataSourceConfig.getDataSourceInfo();

                List<String> readyParam = new ArrayList<>();
                if (sqlCommandType.name().equals("INSERT")) {
                    readyParam = convertUtil.getParamForInsert(parameter);
                } else if (sqlCommandType.name().equals("UPDATE") && !sql.contains("is_deleted=now()")) {
                    readyParam = convertUtil.getParamForUpdate(parameter);
                } else if (sqlCommandType.name().equals("UPDATE") && sql.contains("is_deleted=now()")) {
                    readyParam = convertUtil.getParamForDeleted(parameter);
                }

                sql = convertUtil.setSqlParameters(sql, readyParam);
                Object resObj = executeSql(sqlConnectInfo, sql);

                //生成自增主键id
                if (sqlCommandType.name().equals("INSERT")) {
                    Field idField = parameter.getClass().getDeclaredField("id");
                    idField.setAccessible(true);
                    idField.set(parameter, resObj);
                    result = 1;
                } else result = resObj;
                //插入、更新时version自增
                try {
                    Object param1 = convertUtil.getRealParam(parameter);
                    Field versionField = param1.getClass().getDeclaredField("version");
                    versionField.setAccessible(true);
                    int newVersion = versionField.get(param1) == null ? 1 : Integer.parseInt(versionField.get(param1).toString()) + 1;
                    versionField.set(param1, newVersion);
                } catch (Exception ignored) {
                }
            } catch (Exception e) {
                throw new AutoException(ExceptionEnum.JDBC, "mybatis插件错误 caused by: " + e.getMessage());
            }
        } else result = invocation.proceed();
        return result;
    }

    /*plugin：包装目标对象（为目标对象创建一个代理对象）*/
    @Override
    public Object plugin(Object target) {
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    //将插件注册时的property属性设置进来
    @Override
    public void setProperties(Properties properties) {

    }

}
